package control;

import model.PAppGrid;
import model.PAppRect;
import model.trans_matrix.NeighbourProbData;
import model.trans_matrix.TransitionMatrix;

public class TransMatrixOperations {	
	public void calculateTranProbabilities(TransitionMatrix matrix,PAppGrid grid){
		matrix.resetMatrix();
		int rowNumber=0,colNumber=0;
		for (PAppRect[] row:grid.getSquareGrid()) {
    	colNumber=0;
			for (PAppRect rect : row) {
      	if(rect.isPath()){
      		NeighbourProbData probData = getProbOfNeighbours(new NeighbourProbData(), grid, rowNumber, colNumber);
      		int gridNumRows = grid.getSideSize();
      		matrix.setMatrixElement(rowNumber*gridNumRows+colNumber, 			//
      														(rowNumber-1)*gridNumRows+colNumber, 	//arriba
      														probData.upTranProb);									//
      		matrix.setMatrixElement(rowNumber*gridNumRows+colNumber, 			//
      														(rowNumber+1)*gridNumRows+colNumber,	//abajo
      														probData.downTranProb);								//
      		matrix.setMatrixElement(rowNumber*gridNumRows+colNumber, 			//
      														(rowNumber)*gridNumRows+colNumber-1,	//izquierda 
      														probData.leftTranProb);								//
      		matrix.setMatrixElement(rowNumber*gridNumRows+colNumber, 			//
      														(rowNumber)*gridNumRows+colNumber+1, 	//derecha
      														probData.rightTranProb);							//
      	}
      	colNumber++;
      }
      rowNumber++;
	  }
		printMatrix(matrix);
	}
	private NeighbourProbData getProbOfNeighbours(NeighbourProbData probData, PAppGrid grid, int row, int col){
		int neigCount=0;
		try{//izquierda
			if(grid.getSquareGrid()[row][col-1].isPath()){
				probData.leftTranProb = 1;
				neigCount++;
			}
		}catch(Exception e){}
		try{//abajo
			if(grid.getSquareGrid()[row+1][col].isPath()){
				probData.downTranProb = 1;
				neigCount++;
			}
		}catch(Exception e){}
		try{//derecha
			if(grid.getSquareGrid()[row][col+1].isPath()){
				probData.rightTranProb = 1;
				neigCount++;
			}
		}catch(Exception e){}
		try{//arriba
			if(grid.getSquareGrid()[row-1][col].isPath()){
				probData.upTranProb = 1;
				neigCount++;
			}
		}catch(Exception e){}
		if(neigCount!=0){
			probData.divideByConst(neigCount);			
		}		
		return probData;
	}
	public void printMatrix(TransitionMatrix matrix){
		for(int i=0;i<matrix.getSideSize();i++){
			for(int j=0;j<matrix.getSideSize();j++){
				System.out.print(matrix.getMatrixElement(i, j)+"  ");
			}
			System.out.println();
		}
		System.out.println();
	}
}
